<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    var buildTree = function(preorder, inorder) {
    if (!preorder.length) {
        return null
    }
    const val = preorder.shift()
    const index = inorder.findIndex(item => item === val)
    console.log(index);
    const left = inorder.slice(0, index)
    const right = inorder.slice(index + 1)
    return {
        val,
        left: buildTree(preorder.slice(0, index), left),
        right: buildTree(preorder.slice(index), right)
    }
};
console.log(buildTree([3,9,20,15,7],[9,3,15,20,7]));
  </script>
</body>
</html>